package com.javasm.controller;

import com.javasm.entity.User;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@EnableGlobalMethodSecurity(prePostEnabled = true)

public class AuthController {
    @GetMapping("/hell")
    @Secured({"ROLE_admin"})
    public String hell() {
        return "hell";
    }

    // 只要登录就可以访问的接口
    @GetMapping("/hello")
    @PostAuthorize("hasRole('ROLE_admin')")
    public String hello() {
        System.out.println("hellof方法执行了");
        return "hello";
    }

    // 具有 admin 角色的人才能访问的接口
    @GetMapping("/admin/hello")
    @PreAuthorize(("hasAnyAuthority('admin.hello','admin.a')"))
    public String admin() {
        return "admin";
    }
    // 具有 user 角色的人才能访问的接口， 同时，user 能够访问的资源，admin 都能够访问
    @GetMapping("/user/hello")
    @PreAuthorize("hasRole('ROLE_user')")
    @PostFilter("filterObject.username=='fengxiansheng'")
    public List<User> user()
    {
        List<User> list = new ArrayList<>();
        User user = new User();
        user.setUsername("fengxiansheng");
        list.add(user);
        user=new User();
        user.setUsername("admin");
        list.add(user);
        return list;
    }

    @GetMapping("/getUser/hello")
    @PreAuthorize("hasRole('ROLE_user')")
    @PreFilter("filterObject.username=='fengxiansheng'")
    public List<User> getUser(@RequestBody List<User> list)
    {
       for(User user :list){
           System.out.println(user.getUsername());
       }
       return list;
    }
}